var itemAddEditor ;   //在线编辑器
var input_index = 1;  //定义阶梯价格自增索引默认1
//页面初始化完毕后执行此方法
$(function(){
	
	//row!=1时认为是编辑，新增操作时=1，不执行下面
	if(1 != row){
		$('#brandId').val(row.brandId);
		$('#categoryId').val(row.categoryId);
		$("#itemAddForm [name=productName]").val(row.productName);
		$("#itemAddForm [name=productCode]").val(row.productCode);
		$("#itemAddForm [name=unit]").val(row.unit);
		$("#itemAddForm [name=packageInfo]").val(row.packageInfo);
		$("#itemAddForm [name=minBuyNum]").val(row.minBuyNum);
		$("#itemAddForm [name=packageNum]").val(row.packageNum);
		$("#itemAddForm [name=summary]").val(row.summary);
		$("#itemAddForm [name=description]").val(row.description);
		$("input[type=radio][name='saleStatus'][value='"+row.saleStatus+"']").attr("checked",'checked');
		
		TAOTAO.init({
			"pics" : row.imageUrl1,
			"cid" : row.categoryId,
			fun:function(node){
				console.log("回显成功");
//				TAOTAO.changeItemParam(node, "itemeEditForm");
			}
		});
		
		selectBindBrand(row.categoryId);           		  //查询品牌（下拉菜单）
		selectExtendAttrList(row.categoryId,0,row.id);    //查询商品扩展属性
		loadItemSkuList(row.categoryId,2);                //load商品规格列表
		addStepPriceText();                               //加载动态追加阶梯价格方法
		selectItemSkuList(row.id);                        //查询商品规格列表(查与商品id关联的规格)
	}
	
	//创建富文本编辑器
	//itemAddEditor = TAOTAO.createEditor("#itemAddForm [name=desc]");
	itemAddEditor = KindEditor.create("#itemAddForm [name=description]", TT.kingEditorParams);
	//初始化类目选择和图片上传器（里面函数在选择类目后回调,只是新增操作时会用）
	TAOTAO.init({fun:function(node){
		//根据商品的分类id取商品 的规格模板，生成规格信息。第四天内容。
//		TAOTAO.changeItemParam(node, "itemAddForm");
		selectBindBrand(node.id);
		selectExtendAttrList(node.id,0,'');
		loadItemSkuList(node.id,2);
		addStepPriceText();  //加载动态追加阶梯价格方法
		selectItemSkuList();
	}});
	
});

/**
 * 查询扩展属性列表
 */
function selectExtendAttrList(categoryId,usageMode,productId){
	var params = {
			categoryId : categoryId,
			usageMode : usageMode,
			productId : productId
		};
	$.ajax({
		type:"post",
		contentType:"application/json; charset=utf-8",
		url:path+'/item/v1/param/selectattrbyproductid?page=1&rows=10000',
		data:JSON.stringify(params),
		dataType:"json",
		success:function(data){
			if(data.result == 1){
				$("tr").remove(".append_attr_tr");
				if(data.rows != null){
					for(var i in data.rows){
						var html = $('<tr class="append_attr_tr"></tr>');
						 $(html).append('<td>'+data.rows[i].attributeName+': </td>');
						 var td = $('<td  class="append_attr_td"></td>');
						 if(data.rows[i].attributeValues != null){
							 for(var j in data.rows[i].attributeValues){
								 if(data.rows[i].attributeValues[j].checked == '1'){
									 $(td).append('<label><input name="extendAttr'+data.rows[i].id+'" type="radio" checked="checked" value="'+data.rows[i].attributeValues[j].id+'"/>'+data.rows[i].attributeValues[j].valueStr+'</label>');
								 }else{
									 $(td).append('<label><input name="extendAttr'+data.rows[i].id+'" type="radio" value="'+data.rows[i].attributeValues[j].id+'"/>'+data.rows[i].attributeValues[j].valueStr+'</label>');
								 }
							 }
						 }
						 $(html).append(td);
						 $('#extend_attr_div').after(html);
					}
				}
				 
			}
		}
   });
/*	if(productId != ''){
		$.ajax({
			type:"post",
			contentType:"application/json; charset=utf-8",
			url:path+'/item/v1/param/selectattrbyproductid',
			data:productId+'',
			dataType:"json",
			success:function(data){
				if(data.result == 1){
					alert("成功！");
				}
			}
		});
		
	}*/
}

/**
 * 根据分类查询关联品牌，用于下拉菜单
 * @param categoryId
 */
function selectBindBrand(categoryId){
	$.ajax({
		type:"post",
		contentType:"application/json; charset=utf-8",
		url:path+'/item/v1/cat/selectbindbrand',
		data:categoryId+"",
		dataType:"json",
		success:function(data){
			$("#brandId").combobox({
				valueField : 'id',
				textField : 'brandName',
				data : data.brands
			});
		}
   });
}

/**
 * 加载商品规格列表
 */
function loadItemSkuList(categoryId,usageMode){
	$('#itemSkuList_dategrid').datagrid({
		loadMsg : "数据加载中",
//		title:"商品列表",
		border:true,
		fit : false,
		fitColumns : true,
		pagination : false,
		rownumbers : true,
		singleSelect : true,
		onClickRow: onClickRow,
		onAfterEdit: function (rowIndex, rowData, changes) {
			var params={
				 id : rowData.id,   
				 productId : rowData.productId, 
				 skuName: rowData.skuName,
				 weight : rowData.weight,   
				 stock : rowData.stock,   
				 warningStock : rowData.warningStock,   
				 costPrice : rowData.costPrice  
			};
            $.ajax({
            	type : "post",
        		url : path+'/item/v1/updateitemsku',
        		contentType : "application/json; charset=utf-8",
        		datatype : "json",
        		data :JSON.stringify(params),
                success: function(data){
                	if(data.result == 1){
//                		$.messager.alert("提示","修改规格成功！");
                	}else{
                		$.messager.alert("提示","系统异常，请联系管理员！");
                	}
                }
            });
        },
		columns : [ [
//		    {field:	 'checked',checkbox:true},
		    {field : 'id',title : 'ID',	width : 100,align : 'center',hidden : true},
			{field : 'attrValues',	title : '属性',	width : 180,align : 'center',
				formatter: function(value,row,index){
					if(value != null && value != ''){
						var info='';
						for(var i in value){
							var tmp = '<span style="color:black;margin-right:10px;">'+value[i].valueStr+'</span>';
							info+= tmp;
					    }
						return info;
					}
				}
			},
			{field : 'skuName',	title : '货号',		width : 100,align : 'center',
				formatter: function(value,row,index){
					value=value==null?'':value;
					return 	'<input name="skuName" required="required" value="'+value+'" class="easyui-textbox" data-options="min:0,editable:true">';
				},
				editor:{
					type:'textbox'
				}
			},
			{field : 'productLadderPrices',title : '阶梯价',	width : 100,align : 'center',hidden : false,
				formatter: function(value,row,index){
					return '<a href="#" style="color:blue" onClick="openStepPrice('+index+')">查看阶梯价格 </a>';
				},
			},
			{field : 'costPrice',	title : '成本价(元)',		width : 100,align : 'center',
				formatter: function(value,row,index){
					value=value==null?0:value;
					return 	'<input name="costPrice" required="required" value="'+value+'" class="easyui-numberspinner" data-options="min:0,editable:true">';
				},
				editor:{
					type:'textbox'
				}
			},
			{field : 'stock',	title : '库存',		width : 100,align : 'center',
				formatter: function(value,row,index){
					value=value==null?0:value;
					return 	'<input name="stock" required="required" value="'+value+'" class="easyui-numberspinner" data-options="min:0,editable:true">';
				},
				editor:{
					type:'textbox'
				}
			},
			{field : 'warningStock',	title : '警戒库存',		width : 100,align : 'center',
				formatter: function(value,row,index){
					value=value==null?0:value;
					return 	'<input name="warningStock" required="required" value="'+value+'" class="easyui-numberspinner" data-options="min:0,editable:true">';
				},
				editor:{
					type:'textbox'
				}
			},
			{field : 'weight',	title : '重量(克)',		width : 100,align : 'center',
				formatter: function(value,row,index){
					value=value==null?0:value;
					return 	'<input name="weight" required="required" value="'+value+'" class="easyui-numberspinner" data-options="min:0,editable:true">';
				},
				editor:{
					type:'textbox'
				}
			},
			{field : 'cz',title : '操作',	width : 50,align : 'center',hidden : false,
				formatter: function(value,row,index){
				    return '<a href="#" style="color:blue" onClick="deleteItemSku('+index+')">删除 </a>';
				}
			}
		] ],
		toolbar : [ {
			text : '添加规格',
			iconCls : 'icon-add',
			handler : function() {
				addItemSku(categoryId,usageMode);
			}
		}]
	});
}

var editIndex = undefined;
function endEditing(){
	if (editIndex == undefined){return true;}
	if ($('#itemSkuList_dategrid').datagrid('validateRow', editIndex)){
		$('#itemSkuList_dategrid').datagrid('endEdit', editIndex);
		editIndex = undefined;
		return true;
	} else {
		return false;
	}
}

/**
 * 点击行进行行编辑操作
 * @param index
 */
function onClickRow(index){
	if (editIndex != index){
		if (endEditing()){
			$('#itemSkuList_dategrid').datagrid('selectRow', index).datagrid('beginEdit', index);
			editIndex = index;
		} else {
			$('#itemSkuList_dategrid').datagrid('selectRow', editIndex);
		}
	}
}


/**
 * 查询商品规格列表
 */
function selectItemSkuList(productinfoId){
	var params={};
	if(productinfoId != ''){
		params={productinfoId:productinfoId};
	}
	$.ajax({
		type:"post",
		contentType:"application/json; charset=utf-8",
		url:path+'/item/v1/selectitemsku',
		data:JSON.stringify(params),
		dataType:"json",
		success:function(data){
			if(data.result == 1){
//	    		$.messager.alert("提示","操作成功！");
	    		//当前判断处理 没有数据的情况 必要
				if(data == undefined){
					$('#itemSkuList_dategrid').datagrid('loadData', { total: 0, rows: [] }); 
				}else{
					$('#itemSkuList_dategrid').datagrid('loadData',data);
				}
	    	}else{
//	    		$.messager.alert("提示",data.msg);
	    	}
		}
   });
}

/**
 * 查看阶梯价格
 * @param value
 */
function openStepPrice(index){
	loadStepPriceList();
	$('#stepprice_datagrid').datagrid('loadData', { total: 0, rows: [] });
	var rows = $("#itemSkuList_dategrid").datagrid("getRows");
	for(var i = 0;i<rows[index].productLadderPrices.length;i++){
//		var count = rows[index].productLadderPrices[i].attributeId.split('_');
		$('#stepprice_datagrid').datagrid('appendRow',{
			countbegin: rows[index].productLadderPrices[i].minCount,
			countend: rows[index].productLadderPrices[i].maxCount,
			stepprice: rows[index].productLadderPrices[i].price
		});
	}
	//弹出阶梯价格dialog
	$('#stepPriceDialog').dialog({
		closed: false,
	    cache: false,
	    modal: true,
	    width: 400,
	    height:300
	});
}

/**
 * 加载商品规格列表
 */
function loadStepPriceList(){
	$('#stepprice_datagrid').datagrid({
		loadMsg : "数据加载中",
//		title:"商品列表",
		border:true,
		fit : true,
		fitColumns : true,
		pagination : false,
		rownumbers : true,
		singleSelect : true,
		columns : [ [
			{field : 'countbegin',	title : '起始数量',	width : 100,align : 'center'},
			{field : 'countend',	title : '结束数量',	width : 100,align : 'center'},
			{field : 'stepprice',	title : '阶梯价',  	width : 100,align : 'center'}
		] ]
	});
}

/**
 * 点击添加规格触发，弹出window
 * @param categoryId
 * @param usageMode
 */
function addItemSku(categoryId,usageMode){
//	console.log("addItemSku(categoryId,usageMode)---usageMode==="+usageMode);
	loadItemSkuValueList();
	selectAttributeAdd(categoryId,usageMode);
	$('#AddItemSkuWindow').window('open'); 
}

/**
 * 加载商品规格属性值列表
 */
function loadItemSkuValueList(){
	$('#itemSkuValueList_dategrid').datagrid({
		loadMsg : "数据加载中",
//		title:"规格属性",
		border:true,
		fit : true,
		fitColumns : true,
		pagination : true,
		rownumbers : true,
		singleSelect : true,
		columns : [ [
//		    {field:	 'checked',checkbox:true},
		    {field : 'id',title : 'ID',	width : 40,align : 'center',hidden : true},
			{field : 'attributeName',	title : '属性名称',	width : 40,align : 'center',
				formatter: function(value,row,index){
					return 	value;
				}
			},
			{field : 'attributeValues',	title : '属性值',		width : 100,align : 'center',
				formatter: function(value,row,index){
					if(value != null && value != ''){
						var info='';
						for(var i in value){
							var tmp = '<label><input name="extendSku'+row.id+'" type="radio" value="'+value[i].id+'"/>'+value[i].valueStr+'</label>';
							info+= tmp;
					    }
						return info;
					}
				}
			}
		] ]
	});
}

/**
 * 查询属性列表（带分页）
 * @param categoryId
 * @param usageMode
 */
function selectAttributeAdd(categoryId,usageMode){
	var params = {
			categoryId : categoryId,
			usageMode : usageMode
		};
	$("#itemSkuValueList_dategrid").datagrid_pagination($("#itemSkuValueList_dategrid"),path+"/item/v1/param/selectattr",params,"","");
}

/**
 * 追加阶梯价格
 */
function addStepPriceText(){
	$(".stepprice_class").children().children(".easyui-linkbutton").unbind('click');
	$(".stepprice_class").children().children(".easyui-linkbutton").click(function(){
		$(this).parent().parent().parent().children().last().after(
				'<div class="stepprice_class" style="width: 98%;height: 30px;padding-left: 2%;margin-top: 20px;">'
			        +'<div class="stepprice_child_class" style="width:60%;height:30px;float:left;">'
				        +'<input id="pricebegin'+input_index+'" name="pricebegin'+input_index+'" required="required" value="0" class="easyui-numberspinner" data-options="min:0,editable:true"><label>-</label>' 
				        +'<input id="priceend'+input_index+'"   name="priceend'+input_index+'"   required="required" value="0" class="easyui-numberspinner" data-options="min:0,editable:true">&nbsp'
				        +'<input id="price'+input_index+'"      name="price'+input_index+'"      required="required" value="1" class="easyui-numberspinner" data-options="min:0,editable:true" precision="2"><label>元</label>'
		            +'</div>'
			        +'<div style = "width:30%;height:30px;float:left;margin-left:5px;">'
		               +'<a href="javascript:void(0)"  class="easyui-linkbutton" iconCls="icon-remove"  plain="true" ></a>'
		           +'</div>'
		        +'</div>'
				);
		$.parser.parse($(this).parent().parent().parent().children().last());
		$(this).parent().parent().parent().children().last().children().children(".easyui-linkbutton").click(function() {
			$(this).parent().parent().remove();
		});
		input_index++; //点击一次后，索引增加1
	});
}

/**
 * 保存添加的规格属性
 */
function saveItemSku(){
	
	//拼接已选规格属性
	var paramJsonString = '';
	var paramJson = [];
	$("#AddItemSkuWindow label").each(function(i,e){
		var trs = $(e).find("input[type='radio']:checked");
		if(undefined != trs.val()){
			paramJsonString += trs.val();
			paramJson.push(parseInt(trs.val()));
		}
	});

	//根据页面有的值和拼接的值比较，看是否重复
	var rows = $("#itemSkuList_dategrid").datagrid("getRows");
	for(var i = 0;i<rows.length;i++){
		var info='';
		for(var j in rows[i].attrValues){
			var tmp = rows[i].attrValues[j].id;
			info+= tmp;
	    }
		if($.trim(info) == $.trim(paramJsonString)){
			$.messager.alert("提示","已添加该规格!!!");
			return;
		}
	}
	
	//拼接阶梯价格
	var ps = [];
	for(var i= 0;i<input_index;i++){
//		console.log("起始值"+i+"===="+$("input[name='pricebegin"+i+"']").val());
		var trs0 = $("input[name='pricebegin"+i+"']");
		var trs1 = $("input[name='priceend"+i+"']");
		var trs2 = $("input[name='price"+i+"']");
		if(undefined != trs0.val() && undefined != trs1.val() && undefined != trs2.val()){
			ps.push(trs0.val()+'_'+trs1.val()+','+trs2.val());
		}
	}
	
	var productinfoId = '';
	if( 1 != row){
		productinfoId = row.id;
	}
	
	var params={
		attributeIds : paramJson,
		stepprices : ps,
		productinfoId :productinfoId
	};
	$.ajax({
		type:"post",
		contentType:"application/json; charset=utf-8",
		url:path+'/item/v1/insertitemsku',
		data:JSON.stringify(params),
		dataType:"json",
		success:function(data){
			if(data.result == 1){
//	    		$.messager.alert("提示","操作成功！");
	    		$('#AddItemSkuWindow').window('close');
	    		selectItemSkuList(productinfoId);
	    	}else{
	    		$.messager.alert("提示",data.msg);
	    	}
		}
   });
	
}

/**
 * 删除商品规格以及其关联属性
 */
function deleteItemSku(index){
	var rows = $("#itemSkuList_dategrid").datagrid("getRows");
	var id = rows[index].id;
//	console.log("id===="+id);
//	var productinfoId = 0;
//	if( 1 != row){
//		productinfoId = row.id;
//	}
	var params={
			id : id
//			productinfoId:productinfoId
		};
		$.ajax({
			type:"post",
			contentType:"application/json; charset=utf-8",
			url:path+'/item/v1/deleteitemsku',
			data:JSON.stringify(params),
			dataType:"json",
			success:function(data){
				if(data.result == 1){
//		    		$.messager.alert("提示","操作成功！");
					var productinfoId = 0;
					if( 1 != row){
						productinfoId = row.id;
					}
		    		selectItemSkuList(productinfoId);
		    	}else{
		    		$.messager.alert("提示",data.msg);
		    	}
			}
	   });
}

/**
 * 提交表单（保存）
 */
function submitForm(){
	//有效性验证
	if(!$('#itemAddForm').form('validate')){
		$.messager.alert('提示','表单还未填写完成!');
		return ;
	}
	//同步文本框中的商品描述
	itemAddEditor.sync();
	
	//拼接扩展属性值
	var extendattrs = '';
	$("#itemAddForm tr .append_attr_td").each(function(i,e){
		var trs = $(e).find("input[type='radio']:checked");
		if(trs.val() != undefined){
			extendattrs += trs.val()+',';
		}
	});
	$("#itemAddForm [name=extendattrs]").val(extendattrs);
	
	//拼接商品规格id
	var skuids = '';
	var rows = $("#itemSkuList_dategrid").datagrid("getRows");
	for(var i = 0;i<rows.length;i++){
		if(rows[i].id != undefined){
			skuids +=rows[i].id+',';
		}
	}
	$("#itemAddForm [name=skuids]").val(skuids);
	
	//修改
	if(1 != row){
		$("#itemAddForm [name=id]").val(row.id);
		//ajax的post方式提交表单
		//$("#itemAddForm").serialize()将表单序列化为key-value形式的字符串
		$.post("/item/v1/updateiteminfo",$("#itemAddForm").serialize(), function(data){
			if(data.result == 1){
				$.messager.alert('提示','修改商品成功!');
			}
		});
	//增加
	}else{
		//ajax的post方式提交表单
		//$("#itemAddForm").serialize()将表单序列化为key-value形式的字符串
		$.post("/item/v1/additeminfo",$("#itemAddForm").serialize(), function(data){
			if(data.result == 1){
				$.messager.alert('提示','新增商品成功!');
			}
		});
	}
	
}

/**
 * 重置操作，清空表单
 */
function clearForm(){
	$('#itemAddForm').form('reset');
	itemAddEditor.html('');
}

/**
 * 上传文件方法
 */
function upload(){
	$.ajaxFileUpload({
		url:path+'/upload',
		secureuri:false,
		fileElementId:'file_ggs',
		dataType:'text',
		success:function(data){
			if(data!=null){
				var url = data.substring(data.indexOf('"url":"')+7,data.lastIndexOf('"}</pre>'));
				$.messager.alert("提示","上传成功！");
				console.log("上传规格书路径！"+url);
				$("#itemAddForm [name=specification]").val(url);
			}
		},
		error:function(data){
			console.log("上传失败！");
		}
	});
}